import {HxError} from './hx-error';
import {HttpCode} from './http-code';
import {getBaseUrl, setBaseUrl} from './hx-config';
import {HxMock} from './hx-mock';
import {hxParam} from '../config/hx-param';

export const HxLogin = () => {
    return new Promise((resolve, reject) => {
        if (hxParam.openid) {
            resolve()
        } else {
            uni.login({
                success: res => {
                    HxPost('userInfo', {code: res.code})
                        .then((res) => {
                            uni.setStorageSync('openid', res.openid);
                            resolve();
                        })
                        .catch((err) => {
                            reject(err);
                        });
                }
            })
        }
    });
};

export const HxPost = (httpCode, param, index = 0) => {
    return HxPostReal(httpCode, param)
        .catch((err) => {
            if (['timeout', 'httpError'].includes(err.retCode) && index < 3) {
                setBaseUrl();
                return HxPost(httpCode, param, ++index);
            }
            return Promise.reject(err);
        });
};

export const HxPostReal = (httpCode, param) => {
    if (HxMock.isMock) {
        console.log(httpCode, HxMock[httpCode]);
        return Promise.resolve(HxMock[httpCode]);
    }
    return new Promise((resolve, reject) => {
        console.log('uni.request')
        uni.request(new HxRequest(HxPostParam(httpCode, param, httpCode !== 'userInfo' ? hxParam.openid : '0000'), getBaseUrl()))
            .then((res) => {
                console.log('res', res)
                const err = res[0];
                console.log('err1', err)
                if (err) {
                    if (err.errMsg === 'request:fail timeout') {
                        reject(new HxError('请求超时', 'timeout'));
                    }
                    reject(new HxError(err.errMsg, 'httpError'));
                } else {
                    const data = res[1].data;
                    if (data.retCode !== '0000') {
                        reject(data);
                    } else {
                        resolve(Object.assign({}, data.BizBodyMsg, {retMsg: data.retMsg || ''}));
                    }
                }
            })
            .catch((err) => {
                console.log('err', err)
                if (err.errMsg === 'request:fail timeout') {
                    reject(new HxError('请求超时', 'timeout'));
                }
                reject(new HxError(err.errMsg, 'httpError'));
            });
    });
};


export class HxRequest {
    data;
    url;
    timeout;
    method;
    header;

    constructor (data = {}, url, timeout = 5 * 1000, method = 'POST', header = {'content-type': 'application/json'}) {
        this.data = data;
        this.url = url;
        this.timeout = timeout;
        this.method = method;
        this.header = header;
    }
}

export const HxPostParam = (url, param, userId) => {
    return {
        msg: {
            AppCode: HttpCode[url].AppCode,
            BizCode: HttpCode[url].BizCode,
            BizBodyMsg: param,
            UserId: userId
        },
        sign: '123456'
    };
};



